{
 "cells": [
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "tensor([[-0.1249,  0.0773,  0.0663,  0.2637, -0.0300,  0.1185,  0.2090, -0.0754,\n          0.0281,  0.0312],\n        [-0.1201,  0.1348,  0.1840,  0.1568, -0.1535,  0.0356,  0.0206,  0.0984,\n          0.0494,  0.0602]], grad_fn=<AddmmBackward0>)"
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "from torch.nn import functional as F\n",
    "\n",
    "net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))\n",
    "\n",
    "X = torch.rand(2, 20)\n",
    "net(X)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T01:58:00.141465Z",
     "start_time": "2025-02-26T01:57:58.360634Z"
    }
   },
   "id": "d2a5229b1bf22fec",
   "execution_count": 1
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "tensor([[ 0.0490, -0.0537, -0.0145,  0.1102, -0.0589, -0.0689, -0.0043, -0.0416,\n         -0.1161, -0.0893],\n        [ 0.1344, -0.1925, -0.1264,  0.0969, -0.2044, -0.0965,  0.1039,  0.0513,\n         -0.1566, -0.0646]], grad_fn=<AddmmBackward0>)"
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class MLP(nn.Module):\n",
    "    # 用模型参数声明层。这里，我们声明两个全连接的层\n",
    "    def __init__(self):\n",
    "        # 调用MLP的父类Module的构造函数来执行必要的初始化。\n",
    "        # 这样，在类实例化时也可以指定其他函数参数，例如模型参数params（稍后将介绍）\n",
    "        super().__init__()\n",
    "        self.hidden = nn.Linear(20, 256)  # 隐藏层\n",
    "        self.out = nn.Linear(256, 10)  # 输出层\n",
    "\n",
    "    # 定义模型的前向传播，即如何根据输入X返回所需的模型输出\n",
    "    def forward(self, X):\n",
    "        # 注意，这里我们使用ReLU的函数版本，其在nn.functional模块中定义。\n",
    "        return self.out(F.relu(self.hidden(X)))\n",
    "\n",
    "net = MLP()\n",
    "net(X)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T02:00:11.972505Z",
     "start_time": "2025-02-26T02:00:11.964684Z"
    }
   },
   "id": "33b551d91efb2676",
   "execution_count": 2
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "class MySequential(nn.Module):\n",
    "    def __init__(self, *args):\n",
    "        super().__init__()\n",
    "        for idx, module in enumerate(args):\n",
    "            # 这里，module是Module子类的一个实例。我们把它保存在'Module'类的成员\n",
    "            # 变量_modules中。_module的类型是OrderedDict\n",
    "            self._modules[str(idx)] = module\n",
    "\n",
    "    def forward(self, X):\n",
    "        # OrderedDict保证了按照成员添加的顺序遍历它们\n",
    "        for block in self._modules.values():\n",
    "            X = block(X)\n",
    "        return X"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T02:09:18.554720Z",
     "start_time": "2025-02-26T02:09:18.550002Z"
    }
   },
   "id": "3f2cdb560dedcbfc",
   "execution_count": 3
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "tensor([[ 0.0434, -0.1943, -0.0938,  0.2414,  0.0382, -0.3032, -0.0973,  0.2939,\n          0.0504,  0.2104],\n        [ 0.0702, -0.2530, -0.0869,  0.3790,  0.0096, -0.3256, -0.0875,  0.2352,\n          0.0476,  0.3185]], grad_fn=<AddmmBackward0>)"
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))\n",
    "net(X)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-02-26T02:09:29.813196Z",
     "start_time": "2025-02-26T02:09:29.807077Z"
    }
   },
   "id": "dc1f237745fb2423",
   "execution_count": 4
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   },
   "id": "99bba4328bf25759"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
